package com.hupu.jrs.widget

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Bitmap
import android.os.Build
import android.util.AttributeSet
import android.webkit.*
import com.hupu.jrs.BuildConfig
import com.hupu.jrs.components.jockeyjs.*
import com.hupu.jrs.util.NetWorkUtil
import java.net.URI

/**
 * Created by sll on 2015/6/17.
 */
class JockeyJsWebView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : WebView(context, attrs) {
    private var jockey: Jockey? = null
    private var jockeyAsyncHandler: JockeyAsyncHandler? = null
    private var callback: H5Callback? = null

    var onScrollChangedCallback: OnScrollChangedCallback? = null

    init {
        initWebView()
    }

    @SuppressLint("WrongConstant")
    private fun initWebView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(BuildConfig.DEBUG)
        }
        val settings = settings
        settings.javaScriptEnabled = true
        settings.allowFileAccess = true
        settings.layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS
        settings.useWideViewPort = true
        settings.setSupportZoom(false)
        settings.builtInZoomControls = false
        settings.setSupportMultipleWindows(true)
        settings.defaultTextEncodingName = "UTF-8"
        if (Build.VERSION.SDK_INT > 12) {
            settings.javaScriptCanOpenWindowsAutomatically = true
        }
        settings.setAppCacheEnabled(true)
        settings.loadWithOverviewMode = true
        settings.domStorageEnabled = true
        settings.cacheMode = if (NetWorkUtil.isNetworkConnected(context))
            WebSettings.LOAD_DEFAULT
        else
            WebSettings.LOAD_CACHE_ELSE_NETWORK
        settings.cacheMode = 2
        if (Build.VERSION.SDK_INT > 11) {
            setLayerType(0, null)
        }
    }

    fun initJockey() {
        jockeyAsyncHandler = object : JockeyAsyncHandler() {
            protected override fun doPerform(payload: Map<Any, Any>) {
                if (callback != null) {
                    callback!!.doPerform(payload)
                }
            }
        }

        if (jockey == null) {
            jockey = JockeyImpl.default
        }
        jockey!!.configure(this)
        jockey!!.setWebViewClient(object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                try {
                    if (!isJockeyScheme(URI(url))) {
                        if (callback != null) {
                            callback!!.openBrowser(url)
                        }
                        return true
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }

                return super.shouldOverrideUrlLoading(view, url)
            }

            override fun onPageStarted(view: WebView, url: String, favicon: Bitmap) {
                super.onPageStarted(view, url, favicon)
                if (callback != null) {
                    callback!!.onPageStarted(view, url, favicon)
                }
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                if (callback != null) {
                    callback!!.onPageFinished(view, url)
                }
            }

            override fun onReceivedError(view: WebView, request: WebResourceRequest,
                                         error: WebResourceError) {
                super.onReceivedError(view, request, error)
                if (callback != null) {
                    callback!!.onReceivedError(view, request, error)
                }
            }
        })
        setJockeyEvents()
    }

    fun isJockeyScheme(uri: URI): Boolean {
        return uri.scheme == "jockey" && uri.query != ""
    }

    protected fun setJockeyEvents() {
        if (callback != null) {
            callback!!.setJockeyEvents()
        }
    }

    fun onJSEvent(str: String, jockeyAsyncHandler: JockeyAsyncHandler) {
        if (jockey != null) {
            jockey!!.on(str, jockeyAsyncHandler)
        }
    }

    fun onJSEvent(str: String, handler: JockeyHandler) {
        if (jockey != null) {
            jockey!!.on(str, handler)
        }
    }

    fun sendMessageToJS(str: String, `object`: Any) {
        if (jockey != null) {
            jockey!!.send(str, this, `object`)
        }
    }

    fun sendMessageToJS(str: String, `object`: Any, jockeyCallback: JockeyCallback?) {
        if (jockey != null && jockeyCallback != null) {
            jockey!!.send(str, this, `object`, jockeyCallback)
        }
    }

    fun setCallback(callback: H5Callback) {
        this.callback = callback
    }

    override fun destroy() {
        jockey!!.configure(null!!)
        webChromeClient = null
        webViewClient = null
        super.destroy()
    }

    override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
        super.onScrollChanged(l, t, oldl, oldt)

        if (onScrollChangedCallback != null) {
            onScrollChangedCallback!!.onScroll(l - oldl, t - oldt)
        }
    }

    interface OnScrollChangedCallback {
        fun onScroll(dx: Int, dy: Int)
    }
}
